import 'package:flutter/material.dart';
import 'package:wechat/pages/const.dart';
import 'package:wechat/pages/friend/friends_cell.dart';
import 'package:wechat/pages/friend/index_bar.dart';
import 'friends_data.dart';
import '../discover/discover_detail_page.dart';

class FriendsPage extends StatefulWidget {
  const FriendsPage({Key? key}) : super(key: key);

  @override
  State<FriendsPage> createState() => _FriendsPageState();
}

class _FriendsPageState extends State<FriendsPage> with AutomaticKeepAliveClientMixin<FriendsPage>{
  final _listData = <Friends>[];
  ScrollController _controller = ScrollController();
  final Map groupsOffsetMap = {
    indexWords[0]: 0.0,
    indexWords[1]: 0.0,
    // 'A': 54*4,
  };
  var _listViewH = 0.0;
  @override
  void initState() {
    super.initState();
    _listData..addAll(datas)..addAll(datas);
    _listData.sort( (Friends f1, Friends f2) {
      return f1.firstLetter!.compareTo(f2.firstLetter!);
    });
    //A默认偏移
    var _groupOffset = 54 * headers.length;
    for (int i = 0; i < _listData.length; i++) {
      if (i < 1) {
        groupsOffsetMap.addAll({_listData[i].firstLetter: _groupOffset});
        _groupOffset += 54+30;
      }else if (_listData[i].firstLetter == _listData[i-1].firstLetter) { //没有头部
        _groupOffset += 54;
      }else { //有头
        groupsOffsetMap.addAll({_listData[i].firstLetter: _groupOffset});
        _groupOffset += 84;
      }
    }
    _listViewH = _groupOffset.toDouble();

  }
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "通讯录",
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
        backgroundColor: wechatThemeColor,
        actions: [
          // ElevatedButton(
          //   onPressed: () {
          //     Navigator.of(context).push(
          //         MaterialPageRoute(
          //             builder: (BuildContext ctx) => DiscoverDetailPage("添加朋友")
          //         ),
          //     );
          //   },
          //   child: Image(image: AssetImage("images/friends/添加朋友.png"), width: 40,),
          //   style: ButtonStyle(backgroundColor: MaterialStateProperty.all(Colors.transparent)),
          // )
          GestureDetector(
            onTap: () {
              Navigator.of(context).push(
                MaterialPageRoute(
                    builder: (BuildContext ctx) => DiscoverDetailPage("添加朋友")
                ),
              );
            },
            child: Container(
              padding: EdgeInsets.only(right: 10),
                child: Image(
                  image: AssetImage("images/friends/添加朋友.png"),
                  width: 30,
                )
            ),
          ),

        ],
      ),
      body: Stack(children: [
        Container(
          color: wechatThemeColor,
          child: ListView.builder(
            controller: _controller,
              itemCount: _listData.length + headers.length,
              itemBuilder: (BuildContext context, int index) {
                return _itemForRow(context, index);
              }),
        ),
        IndexBar(
          indexBarCallback: (title) {
            num? offsetY = groupsOffsetMap[title];
            if (offsetY != null) {
              if (offsetY > _controller.position.maxScrollExtent) {
                offsetY =  _controller.position.maxScrollExtent;
              }
              _controller.animateTo(offsetY.toDouble(), duration: Duration(milliseconds: 10), curve: Curves.easeIn);
            }

          },
        ),
      ]),
    );
  }

  Widget _itemForRow(BuildContext context, int index) {
    if (index < headers.length) {
      return FriendsCell(
        assetImage: headers[index].imageUrl,
        username: headers[index].username,
      );
    }
    if (index > headers.length && _listData[index-headers.length].firstLetter == _listData[index-headers.length-1].firstLetter) {
      return FriendsCell(
        imageUrl: _listData[index-headers.length].imageUrl,
        username: _listData[index-headers.length].username,
      );
    }
    return FriendsCell(
      imageUrl: _listData[index-headers.length].imageUrl,
      username: _listData[index-headers.length].username,
      firstLetter: _listData[index-headers.length].firstLetter,
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    print("通讯录界面销毁了");
    super.dispose();
  }
}
